﻿using Meiam.System.Interfaces;
using Meiam.System.Interfaces.IService;
using Meiam.System.Model.Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Meiam.System.Model.Dto;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SqlSugar;
using System.Text;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Meiam.System.Model;
using Microsoft.Extensions.Logging;
using OfficeOpenXml.FormulaParsing.Excel.Functions.RefAndLookup;
using System.Web;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Math;

namespace Meiam.System.Hostd.Controllers.Gokin
{
    /// <summary>
    /// 靶向发货AI运算结果
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class BXAIComputeController : ControllerBase
    {
        private readonly ILogger<BXAIComputeRequestDto> _logger;
        public readonly IWMSTokenCheckService _WMSTokenCheckService;
        public readonly string con;


        public BXAIComputeController(ILogger<BXAIComputeRequestDto> logger,IWMSTokenCheckService wmsTokenCheckService, IConfiguration _configuration)
        {
            _logger = logger;
            _WMSTokenCheckService = wmsTokenCheckService;
             con= _configuration.GetConnectionString("DDM_DbConnection_ZH");

        }

        /// <summary>
        /// 靶向发货AI运算结果
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PostBXAICompute([FromBody] BXAIComputeRequestDto strparm)
        {
            string  strMsg = "";
            object log = "";
            log = strparm;
            StringBuilder strSql = new StringBuilder();
            StringBuilder strSqlFine = new StringBuilder();
            List<string> strSqlList = new List<string>();
            BXAIComputeResponseDto re = new BXAIComputeResponseDto();
            var row = strparm.rows;


            //框架查询方法
            //var data = _WMSTokenCheckService.GetTokenCheckData(supplier_code);

            try
            {
                foreach (var rows in row)
                {
                    string ccode = rows.ccode;
                    string materialcode = rows.materialcode;
                    string customer_name = rows.customer_name;
                    double materialamount =DB.ToDouble(rows.materialamount);
                    strSql = new StringBuilder();
                    strSql.Append(@"select *  from iwms_sql_temp where 1=1 and  pzid='SYS0003'");
                    DataTable dt_sql = DB.Query(strSql.ToString(), con);
                    if (dt_sql.Rows.Count <= 0)
                    {
                        strMsg = "无数据，请检查清楚再调用接口";
                    }
                    else
                    {
                        string temp_sql = dt_sql.Rows[0]["temp_info"].ToString()+ " and ma.customer_shortname='"+ customer_name + "' and  jz.material_code='"+ materialcode + "' order by remark_priority  ";

                        DataTable dt_customerxq = DB.Query(temp_sql, con);

                        string barcode_remark = "";
                        double average_thickness = 0;
                        double begin_resistance = 0;
                        double end_resistance = 0;
                        double begin_resistancefocus = 0;
                        double end_resistancefocus = 0;
                        string average_code = "";
                        double tqty = DB.ToDouble(rows.barcode_qty);
                        double ts = 0;


                        int sss = 0;


                        if (dt_customerxq.Rows.Count>0)
                        {
                            average_thickness = DB.ToDouble(dt_customerxq.Rows[0]["average_thickness"].ToString());
                            begin_resistance = DB.ToDouble(dt_customerxq.Rows[0]["begin_resistance"].ToString());
                            end_resistance = DB.ToDouble(dt_customerxq.Rows[0]["end_resistance"].ToString());
                            begin_resistancefocus = DB.ToDouble(dt_customerxq.Rows[0]["begin_resistancefocus"].ToString());
                            end_resistancefocus = DB.ToDouble(dt_customerxq.Rows[0]["end_resistancefocus"].ToString());
                            average_code = dt_customerxq.Rows[0]["average_thickness"].ToString();

                            foreach (DataRow item in dt_customerxq.Rows)
                            {
                                barcode_remark = barcode_remark + "'"+ item["barcode_remark"].ToString().Trim() + "',";
                            }

                            barcode_remark = barcode_remark.TrimEnd(',');

                            ts= Math.Floor(materialamount/ tqty);
                            if (ts>0)
                            {
                                strSqlFine = new StringBuilder();
                                strSqlFine.Append(@"select barcode_no,material_code,material_name,material_amount,remark,IFNULL(average_thickness,0.00)average_thickness,IFNULL(average_resistance,0.00)average_resistance,IFNULL(average_resistancefocus,0.00)average_resistancefocus,ccode,barcode_create_time
from wms_temp_gp_stock where material_code='" + materialcode + "' and  material_amount=" + tqty + " and  remark in(" + barcode_remark + ") and barcode_no not in (select parent_barcode_no from  iwms_targeted_shipment_pallet where is_enable=1)");
                                DataTable dt_remarkfine = DB.Query(strSqlFine.ToString(),con);
                                //按照托备注过滤，库存托数量大于等于需求托数量，往后运算
                                if (dt_remarkfine.Rows.Count>= ts)
                                {

                                    strSqlFine = new StringBuilder();
                                    strSqlFine.Append(@"select barcode_no,material_code,material_name,material_amount,remark,IFNULL(average_thickness,0.00)average_thickness,IFNULL(average_resistance,0.00)average_resistance,IFNULL(average_resistancefocus,0.00)average_resistancefocus,ccode,barcode_create_time
 from wms_temp_gp_stock where material_code='" + materialcode + "' and  material_amount=" + tqty + " and  remark in(" + barcode_remark + ") and barcode_no not in (select parent_barcode_no from  iwms_targeted_shipment_pallet where is_enable=1)  ");
                                    DataTable dt_remarkall = DB.Query(strSqlFine.ToString(), con);
                                    //所有符合需求托数据
                                    re.data3 = DB.TableToListModel<BXAIComputeResponseData3>(dt_remarkall);
                                    //按托均值电阻运算，直到符合
                                    //strSql.Append(@" and ROUND(average_resistance,2)>" + end_resistance + " and ROUND(average_resistance,2)<" + begin_resistance + " order by average_resistance desc ");
                                    //DataTable dt_thicknessfine_no = DB.Query(strSql.ToString(), con);
                                    string  ys ="";
                                   
                                    string sx_remark = "";
                                    string sx_cx_remark = "";

                                    foreach (DataRow ysdt in dt_customerxq.Rows)
                                    {
                                        int yscs = 0;
                                        if (ys=="")
                                        {
                                            sx_remark = sx_remark + "'" + ysdt["barcode_remark"].ToString().Trim() + "',";

                                            sx_cx_remark = sx_remark.TrimEnd(',');

                                            strSql = new StringBuilder();
                                            strSql.Append(@"select barcode_no,material_code,material_name,material_amount,remark,IFNULL(average_thickness,0.00)average_thickness,IFNULL(average_resistance,0.00)average_resistance,IFNULL(average_resistancefocus,0.00)average_resistancefocus,ccode,barcode_create_time
from wms_temp_gp_stock where material_code='" + materialcode + "' and  material_amount=" + tqty + " and  remark in(" + sx_cx_remark + ") and barcode_no not in (select parent_barcode_no from  iwms_targeted_shipment_pallet where is_enable=1) and (average_resistance>0 or average_resistance>0) ");
                                            DataTable dt_ys = DB.Query(strSql.ToString(), con);
                                            if (dt_ys.Rows.Count>= ts)
                                            {
                                                while (ys == "")
                                                {
                                                    if (yscs == 500)
                                                    {
                                                        break;
                                                    }
                                                    else
                                                    {
                                                        ys = AIYS.BXYS(dt_ys, begin_resistance, end_resistance, average_thickness, ts, "average_resistance", "average_thickness");
                                                        yscs++;
                                                    }

                                                }
                                            }
                                            
                                            
                                            sss = sss + yscs;
                                        }

                                      


                                    }


                                    if (ys == "")
                                    {
                                        strMsg = "无符合计划数据，请另选计划匹配！";
                                    }
                                    else
                                    {

                                        strSqlFine.Append(@" and  barcode_no not in(" + ys + ")   order by barcode_create_time");
                                        DataTable dt_aioutput_jy = DB.Query(strSqlFine.ToString(), con);
                                        if (dt_aioutput_jy.Rows.Count >= 0)
                                        {
                                            re.data2 = DB.TableToListModel<BXAIComputeResponseData2>(dt_aioutput_jy);
                                            strSql = new StringBuilder();
                                            strSql.Append(@" select '" + ccode + "'plan_no,kc.*  from wms_temp_gp_stock kc where barcode_no in(" + ys + ")  order by barcode_create_time");
                                            DataTable dt_aioutput = DB.Query(strSql.ToString(), con);
                                            if (dt_aioutput.Rows.Count >0)
                                            {
                                                re.data = DB.TableToListModel<BXAIComputeResponseData>(dt_aioutput);
                                               
                                            }
                                            else
                                            {
                                                strMsg = "运算结果，获取异常，请联系管理员！";
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    strMsg = "库存不满足，现在客户，请稍后再试！";
                                }
                              
                            }
                           






                        }
                        else
                        {
                            strMsg = "获取客户品质配置数据，请维护信息后再进行匹配！";
                        }


                        
                    }



                }
            }
            catch (Exception ex)
            {
                strMsg = ex.ToString();
            }

         


            if (strMsg=="")
            {
                re.status = "成功";
                re.code = "0";
            }
            else
            {
                re.status = "失败";
                re.code = "500";
                re.message = strMsg;
            }


            return new JsonResult(re);
        }

      
    }
}
